← Back

AXIOS IN JAVASCRIPT

Axios is a Promise-based library for making HTTP requests.

This note explains Axios in simple language.

You will learn:

  1. what Axios is
  2. why Axios is convenient
  3. how to install and import it
  4. how to make requests
  5. what axios.get() does
  6. what the response object looks like
  7. how default configuration works
  8. how default headers work
  9. how query parameters work in Axios

1. What is Axios?

Axios is a library for making HTTP requests.

It is based on Promises and is often used instead of fetch() because it makes many things simpler.

With Axios, you can:

Easy definition:

Axios = a convenient HTTP client for JavaScript

Diagram 1. Main idea of Axios

JavaScript code
-> Axios sends HTTP request
-> Server returns response
-> Axios gives response back to your code

Axios sits between your code and the server and makes the communication easier.

2. Why Axios is useful

Axios is popular because it gives you several conveniences:

  1. automatic JSON parsing
  2. easier error handling
  3. easy global settings
  4. cleaner syntax for requests

With fetch(), you often need extra steps like:

Axios does those things more conveniently.

Diagram 2. Fetch vs Axios

fetch()
-> send request
-> check response.ok manually
-> call response.json() manually
-> use data
axios
-> send request
-> Axios parses JSON automatically
-> use response.data

Axios reduces repeated code.

3. Installation

If you use a project with npm, install Axios with:

npm install axios

After that, import it in your JavaScript file:

import axios from "axios";

Now Axios is ready to use.

Diagram 3. Installation flow

npm install axios
-> package added to project
-> import axios from "axios"
-> Axios is ready

4. Basic request syntax

The general Axios form is:

axios({
  method: "get",
  url: "https://jsonplaceholder.typicode.com/users",
});

This call returns a Promise.

That means you handle it with:

Example

import axios from "axios";

axios({
  method: "get",
  url: "https://jsonplaceholder.typicode.com/users",
})
  .then(response => console.log(response))
  .catch(error => console.log(error));

Diagram 4. Axios request flow

Call axios(...)
-> Axios sends request
-> Server responds
-> Promise is fulfilled or rejected
-> then() or catch() runs

Just like fetch(), Axios is asynchronous.

5. What does axios() return?

axios() returns:

Promise

It does not return the data immediately.

The response comes later, so you must use then() and catch().

Diagram 5. What axios() returns

axios(...)
-> Promise
-> then(response)
or
-> catch(error)

6. Why Axios is more convenient than fetch()

There are two very important differences.

6.1 Automatic JSON parsing

With fetch(), you usually do this:

fetch(url)
  .then(response => response.json())
  .then(data => console.log(data));

With Axios, JSON is parsed automatically:

axios.get(url)
  .then(response => console.log(response.data));

So there is no need for:

response.json()

6.2 Automatic error handling for bad HTTP status

With fetch(), even a 404 or 500 usually does not reject automatically.

You often need to check response.ok yourself.

With Axios, unsuccessful HTTP status codes like 404 and 500 usually cause the promise to reject automatically.

So catch() is much more useful immediately.

Diagram 6. Axios convenience

Axios
|
|- parses JSON automatically
`- rejects promise for bad HTTP status

This is why many developers like Axios.

7. Request method aliases

Axios supports the full config object form, but it also gives shorter methods.

For example, instead of:

axios({
  method: "get",
  url: "https://jsonplaceholder.typicode.com/users",
});

you can simply write:

axios.get("https://jsonplaceholder.typicode.com/users");

This is shorter and easier to read.

Diagram 7. Long syntax vs short syntax

Long:
axios({
  method: "get",
  url: "..."
})
Short:
axios.get("...")

The second version is more common for simple GET requests.

8. axios.get()

The method:

axios.get(url[, config])

makes a GET request.

Example

import axios from "axios";

axios.get("https://jsonplaceholder.typicode.com/users")
  .then(response => console.log(response))
  .catch(error => console.log(error));

Here, Axios automatically knows the request method is GET.

So you do not need to write method: "get" again.

Diagram 8. axios.get()

axios.get("URL")
-> Axios sends GET request
-> returns Promise

9. The response object

When Axios receives a response, it gives you a response object.

It looks like this:

{
  data: {},
  status: 200,
  statusText: "OK",
  headers: {},
  config: {},
  request: {}
}

9.1 Main properties

data is the most important property. It contains the response body from the server.

status is the HTTP status code, for example 200, 404, or 500.

statusText is the text for the status, for example "OK".

headers contains the response headers.

config contains the request configuration used by Axios.

request contains information about the request itself.

Diagram 9. Axios response object

response
|
|- data
|- status
|- statusText
|- headers
|- config
`- request

In real work, the most commonly used properties are:

response.data
response.status

10. The most important property: response.data

Server data is stored in:

response.data

Example

import axios from "axios";

axios.get("https://jsonplaceholder.typicode.com/users")
  .then(response => {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  })
  .catch(error => {
    console.log(error);
  });

Diagram 10. Where the data is

Axios response
-> response.data
-> actual data from server

Easy memory rule:

Axios data is in response.data

11. Default configuration

If many requests use the same server address, writing the full URL every time becomes repetitive.

Example:

axios.get("https://jsonplaceholder.typicode.com/users");
axios.get("https://jsonplaceholder.typicode.com/posts");
axios.get("https://jsonplaceholder.typicode.com/images");

A better way is to set:

axios.defaults.baseURL

Example

import axios from "axios";

axios.defaults.baseURL = "https://jsonplaceholder.typicode.com";

After that, you can use only relative paths:

import axios from "axios";

axios.defaults.baseURL = "https://jsonplaceholder.typicode.com";

axios.get("/users").then().catch();
axios.get("/posts").then().catch();
axios.get("/images").then().catch();

Diagram 11. baseURL

Set baseURL once
-> all requests automatically start from that address

This is useful because if the API address changes, you change it in one place only.

12. Why default configuration is useful

Without default config:

full URL in every request

With default config:

base URL once
-> shorter request paths later

Diagram 12. Without vs with baseURL

Without baseURL
-> repeat long address many times
With baseURL
-> write long address once
-> use short paths later

13. Default headers

Besides the base address, Axios also lets you set default headers.

This is useful when every request needs the same header, for example:

The common place is:

axios.defaults.headers.common

Example

import axios from "axios";

const myApiKey = "secret-api-key-for-every-request";

axios.defaults.headers.common["header-name"] = myApiKey;

Real examples could be:

axios.defaults.headers.common["Authorization"] = "Bearer token-value";
axios.defaults.headers.common["X-API-Key"] = "my-secret-key";

Diagram 13. Default headers

Set default header once
-> Axios adds it to every request

This avoids repeating the same header in every request.

14. Important note about default headers

A simple memory rule is:

Common default headers:
axios.defaults.headers.common

This is the most practical place for headers that must go into all requests.

15. Query string parameters

Sometimes you need to send extra conditions in the URL.

For example:

These are query parameters.

You can write them directly in the URL:

axios.get("https://jsonplaceholder.typicode.com/users?_limit=7&_sort=name");

This works, but it becomes messy when there are many parameters.

Diagram 14. Query parameters in URL

/users?_limit=7&_sort=name
      |        |
      |        `- second parameter
      `- first parameter

16. Using URLSearchParams

Another way is:

const searchParams = new URLSearchParams({
  _limit: 5,
  _sort: "name",
});

axios.get(`https://jsonplaceholder.typicode.com/users?${searchParams}`);

This is better than writing a long string manually, but Axios has an even cleaner option.

17. Best Axios way: params

Axios lets you pass query parameters as an object using params.

Example

axios.get("https://jsonplaceholder.typicode.com/users", {
  params: {
    _limit: 7,
    _sort: "name",
  },
});

Axios automatically converts this object into a query string.

Diagram 15. params flow

params object
-> Axios converts it
-> query string in URL
-> request is sent

This is usually the best and cleanest Axios way.

18. Why params is better

Using params is better because:

Diagram 16. Direct URL vs params object

Direct URL
-> harder to read when long
params object
-> cleaner
-> easier to edit
-> Axios builds query automatically

19. Full simple example

Here is a clean Axios example with baseURL and params:

import axios from "axios";

axios.defaults.baseURL = "https://jsonplaceholder.typicode.com";

axios.get("/users", {
  params: {
    _limit: 7,
    _sort: "name",
  },
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

Diagram 17. Full Axios request flow

Set baseURL
-> Call axios.get("/users", { params: ... })
-> Axios builds final URL
-> Request goes to server
-> Response returns
-> Use response.data

20. Common beginner mistakes

Mistake 1. Looking for data in the wrong place

Wrong:

response.value
response.result

Correct:

response.data

Mistake 2. Thinking Axios returns data directly

Wrong idea:

axios.get(...) gives data immediately

Correct idea:

axios.get(...) returns a Promise

Mistake 3. Forgetting to import Axios

If Axios is installed but not imported, it will not work in the file.

Correct:

import axios from "axios";

Mistake 4. Repeating the full URL in every request

If all requests go to the same server, it is better to use:

axios.defaults.baseURL

Mistake 5. Writing long query strings manually

For many parameters, prefer:

params: { ... }

instead of building the whole query string yourself.

Diagram 18. Common mistakes summary

Data is in response.data
Axios returns Promise
Remember import axios
Use baseURL for repeated server address
Use params for query parameters

21. Easy memory rules

Axios = HTTP client based on Promises
axios() = returns Promise
axios.get() = GET request
response.data = server data
axios.defaults.baseURL = common base address
axios.defaults.headers.common = common headers
params = query parameters object

22. Quick summary

23. Final conclusion

If you understand these ideas:

Axios
axios.get()
Promise
response.data
baseURL
default headers
params

then you already have a strong foundation for using Axios in JavaScript.

Axios is very useful in real projects because it makes server communication cleaner, shorter, and easier to maintain.

← Back